package cn.tedu._05mvcboot04.controller;

import cn.tedu._05mvcboot04.mapper.Mapper;
import cn.tedu._05mvcboot04.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot04.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot04.pojo.entity.Article;
import cn.tedu._05mvcboot04.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot04.pojo.vo.UserVO;
import cn.tedu._05mvcboot04.response.JsonResult;
import cn.tedu._05mvcboot04.response.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "01.用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private Mapper mapper;
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult selectUser(@RequestBody UserLoginDTO userLoginDTO,HttpSession session){
        log.debug("userLoginDTO={}",userLoginDTO);
        //获取用户名，密码
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = mapper.selectUser(username, password);
        if (userVO!=null){
            //创建会话
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }
    @ApiOperation(value = "发布文章功能")
    @PostMapping("article")
    public JsonResult insertArticle(@RequestBody @Validated UserArticleDTO userArticleDTO, @Validated HttpSession session){
        log.debug("userArticleDTO={}",userArticleDTO);
        //获取会话
        UserVO userVO =(UserVO)session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        mapper.insertArticle(article);
        return JsonResult.ok();
    }
    @ApiOperation(value = "查询指定文章功能")
    @GetMapping("selectByArticleById")
    @ApiImplicitParam(name = "id",value = "文章ID",required = true,dataType = "Long")
    public JsonResult selectByArticleById(@Range(min = 1,max = 100,message = "文章ID要求1-100之间") Long id){
        ArticleVO articleVO = mapper.selectByArticleId(id);
        return JsonResult.ok(articleVO);
    }
}
